﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.SessionState;
using AD.BLL;
using AD.Model;
using System.Text.RegularExpressions;
using Security.Cryptography;
using System.Threading;
/// <summary>
///RequestHandlerBase 的摘要说明
/// </summary>


enum DateTimeType{
Time,
    Date,DateTime,
}
public class RequestHandlerBase : IRequiresSessionState
{
    private HttpServerUtility server;
    private HttpSessionState sessiom;
    private HttpRequest request;
    private HttpResponse response;
    public HttpServerUtility Server { get { return server; } }
    public HttpRequest Request { get { return request; } }
    public HttpSessionState Session { get { return sessiom; } }
    public HttpResponse Response { get { return response; } }


    //string UpdateFile()
    //{
    //    string fileName = "";
    //    try
    //    {
    //        HttpPostedFile file = Request.Files["ProductPicture"];
    //        if (file != null)
    //        {
    //            fileName = file.FileName;
    //            if (!string.IsNullOrEmpty(fileName))
    //            {
    //                int idx = fileName.LastIndexOf(".");
    //                string suffix = fileName.Substring(idx);//获得上传的图片的后缀名 
    //                fileName = DateTime.Now.ToString("yyyyMMddHhmmssfff") + suffix;
    //                string tmpFileName = Server.MapPath("../Uploads/") + fileName;
    //                file.SaveAs(tmpFileName);
    //            }
    //        }
    //    }
    //    catch { }
    //    return fileName;
    //}

    protected void HandlerRequest()
    {
        string action = Request.Params["action"];
        string userType = Request.Params["ut"];
        if (string.IsNullOrEmpty(userType))
        {
            return;
        }
        if (userType.Equals("ic"))
        {
            if (!string.IsNullOrEmpty(action))
            {
                if (action.Equals("install") && !string.IsNullOrEmpty(Request.QueryString["userName"]))
                {
                    Write(InstallLogBLL.Insert(new InstallLogMod() { LocationMsg = UtilHepler.GetLocation(Request.UserHostAddress), UserName = Request.QueryString["userName"], InstallSource = InstallSource.Plugin, IpAddress = Request.UserHostAddress, CommitDate = DateTime.Now }));
                }
            }
        }
        if (userType.Equals("lc")) {
            string format= Request.QueryString["format"];
            if (string.IsNullOrEmpty(format))
                format = "xml";
            string locationmsg = UtilHepler.QueryLocation(Request.QueryString["ip"], format);
            Write(locationmsg);
        }
        else if (userType.Equals("custom"))
        {
            #region
            if (SessionUser == null)
            {
                if (!string.IsNullOrEmpty(action) && !action.Equals("userlogin"))
                {
                    Write("window.location.replace(\"index.html\")");
                    return;
                }
            }
            switch (action)
            {
                case "lm": {
                    Write(UtilHepler.GetLocation(Request.QueryString["ip"]));
                    break;
                }
                case "paymoney":
                    {
                        Session["paymoney"] = Request.QueryString["pm"];
                        Response.Redirect("../../AliPay/default.aspx");
                        break;
                    }
                case "pinfo":
                    {
                        #region 个人信息
                        UserMod user = UserBLL.QueryById(SessionUser.AutoID);
                        StringBuilder sb = new StringBuilder();
                        if (user == null)
                        {
                            sb.Append("{\"retcode\":-1}");
                            sb.ToString();
                        }
                        else
                            sb.Append("{\"retcode\":1");
                        sb.Append(",");
                        sb.Append(SetValue("CompanyName", user.CompanyName));
                        sb.Append(",");
                        sb.Append(SetValue("Email", user.Email));
                        sb.Append(",");
                        sb.Append(SetValue("MobilePhone", user.MobilePhone));
                        sb.Append(",");
                        sb.Append(SetValue("NetShopAddress", user.NetShopAddress));
                        sb.Append(",");
                        sb.Append(SetValue("NetShopName", user.NetShopName));
                        sb.Append(",");
                        sb.Append(SetValue("Product", user.Product));
                        sb.Append(",");
                        sb.Append(SetValue("QQ", user.QQ));
                        sb.Append(",");
                        sb.Append(SetValue("Recommended", user.Recommended));
                        sb.Append(",");
                        sb.Append(SetValue("TelPhone", user.TelPhone));
                        sb.Append(",");
                        sb.Append(SetValue("UnderstandChannel", user.UnderstandChannel));
                        sb.Append(",");
                        sb.Append(SetValue("Url", user.Url));
                        sb.Append(",");
                        sb.Append(SetValue("WangWang", user.WangWang));
                        sb.Append("}");
                        Write(sb.ToString());
                        break;
                        #endregion
                    }
                case "ilcode":
                    {
                        #region 生成链接
                        string result = UtilHepler.URL + "/index.html?clientkey=" + UtilHepler.ByteToHexX2(new AESHelper().Encrypt(Encoding.UTF8.GetBytes(SessionUser.AutoID.ToString())));
                        Write(result);
                        break;
                        #endregion
                    }
                case "ilif":
                    {
                        #region 赠送链接
                        string strPageIndex = Request.QueryString["pageIndex"];
                        int pageIndex;
                        int.TryParse(strPageIndex, out pageIndex);
                        //string result = Invite_flowToJson(" UserId=" + SessionUser.AutoID, 10, pageIndex);
                        string result = PayTradeToJson(" RewardType=2 and UserId=" + SessionUser.AutoID, 10, pageIndex);
                        Write(result);
                        break;
                        #endregion
                    }
                case "ptif":
                    {
                        #region 资金帐户信息
                        //SessionUser = UserBLL.QueryById(SessionUser.AutoID);
                        string strPageIndex = Request.QueryString["pageIndex"];
                        int pageIndex;
                        int.TryParse(strPageIndex, out pageIndex);
                        string result = PayTradeToJson(" Status=1 and IsInMoney=1 and UserId=" + SessionUser.AutoID, 10, pageIndex);
                        Write(result);

                        break;
                        #endregion
                    }
                case "updateshop":
                    {
                        #region 修改网站推广
                        int retcode = -1;
                        try
                        {
                            if (Request.UrlReferrer == null || string.IsNullOrEmpty(Request.UrlReferrer.AbsoluteUri))
                                return;
                            string t = Request.QueryString["t"];
                            if (string.IsNullOrEmpty(t)) return;
                            NetShopMod shop = NetShopsBLL.QueryById(int.Parse(Request.Form["AutoID"]));
                            //HttpPostedFile file = Request.Files["ProductPicture"];
                            //if (file != null)
                            //{
                            //    string fileName = file.FileName;
                            //    if (!string.IsNullOrEmpty(fileName))
                            //    {
                            //        int idx = fileName.LastIndexOf(".");
                            //        string suffix = fileName.Substring(idx);//获得上传的图片的后缀名 
                            //        fileName = DateTime.Now.ToString("yyyyMMddHhmmssfff") + suffix;
                            //        shop.ProductPicture = fileName;
                            //        fileName = Server.MapPath("..Uploads/") + fileName;
                            //        file.SaveAs(fileName);
                            //    }
                            //}
                            //string pricFile= UpdateFile();
                            //if(!string.IsNullOrEmpty(pricFile))
                            shop.ProductPicture =Request.Form["ProductPicture"];
                            if (t.Equals("tb"))
                                shop.NetShopType = ShopType.Taobao;
                            else
                                shop.NetShopType = ShopType.Paipai;
                            //shop.AutoID = int.Parse(Request.Form["AutoID"]);
                            shop.UserId = SessionUser.AutoID;
                            shop.KeyWords = Request.Form["KeyWords"];
                            shop.ShopName = Request.Form["ShopName"];
                            shop.ProductName = Request.Form["ProductName"];
                            shop.Url = Request.Form["Url"];
                            shop.QQ = Request.Form["QQ"];
                            if (HttpDataCache.AppSettings.IsChangeAudit)
                                shop.Status = KeyWordsStatus.WaitPass;
                            shop.Region = Request.Form["Region"];

                            if (!string.IsNullOrEmpty(Request.Form["ProductPrice"]))
                                shop.ProductPrice = double.Parse(Request.Form["ProductPrice"]);

                            if (!string.IsNullOrEmpty(Request.Form["CommitCount"]))
                                shop.CommitCount = int.Parse(Request.Form["CommitCount"]);

                            if (!string.IsNullOrEmpty(Request.Form["Shipping"]))
                                shop.Shipping = int.Parse(Request.Form["Shipping"]);

                            if (!string.IsNullOrEmpty(Request.Form["IsLogo"]))
                                shop.IsLogo = int.Parse(Request.Form["IsLogo"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsProtection"]))
                                shop.IsProtection = int.Parse(Request.Form["IsProtection"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsRetreat"]))
                                shop.IsRetreat = int.Parse(Request.Form["IsRetreat"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsAllDayShipping"]))
                                shop.IsAllDayShipping = int.Parse(Request.Form["IsAllDayShipping"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsGenuineProtection"]))
                                shop.IsGenuineProtection = int.Parse(Request.Form["IsGenuineProtection"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsCashonDelivery"]))
                                shop.IsCashonDelivery = int.Parse(Request.Form["IsCashonDelivery"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsCreditCard"]))
                                shop.IsCreditCard = int.Parse(Request.Form["IsCreditCard"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsPublicbaby"]))
                                shop.IsPublicbaby = int.Parse(Request.Form["IsPublicbaby"]) == 1 ? true : false;
                            retcode = NetShopsBLL.UpdateInfo(shop);
                        }
                        finally
                        {
                            Response.Redirect("ShopList.aspx?action=gopage&pageIndex=" + Request.QueryString["pageIndex"]);
                        }
                        break;
                        #endregion
                    }
                case "editshop":
                    {
                        #region
                        int id;
                        int.TryParse(Request.QueryString["id"], out id);
                        NetShopMod shops = NetShopsBLL.QueryById(id);
                        string result = "var shop={\"retcode\":-1}";
                        if (shops != null)
                            result = "{" +
                                            "\"retcode\":1," +
                                            "\"AutoID\":" + shops.AutoID + "," +
                                            "\"CommitCount\":" + shops.CommitCount + "," +
                                            "\"IsAllDayShipping\":" + shops.IsAllDayShipping.ToString().ToLower() + "," +
                                            "\"IsCashonDelivery\":" + shops.IsCashonDelivery.ToString().ToLower() + "," +
                                            "\"IsCreditCard\":" + shops.IsCreditCard.ToString().ToLower() + "," +
                                            "\"IsGenuineProtection\":" + shops.IsGenuineProtection.ToString().ToLower() + "," +
                                            "\"IsLogo\":" + shops.IsLogo.ToString().ToLower() + "," +
                                            "\"IsProtection\":" + shops.IsProtection.ToString().ToLower() + "," +
                                            "\"IsPublicbaby\":" + shops.IsPublicbaby.ToString().ToLower() + "," +
                                            "\"IsRetreat\":" + shops.IsRetreat.ToString().ToLower() + "," +
                                            "\"IsUse\":" + shops.IsUse.ToString().ToLower() + "," +
                                            "\"KeyWords\":\"" + shops.KeyWords + "\"," +
                                            "\"NetShopType\":" + (int)shops.NetShopType + "," +
                                            "\"ProductName\":\"" + shops.ProductName + "\"," +
                                            "\"ProductPicture\":\"" + shops.ProductPicture + "\"," +
                                            "\"ProductPrice\":" + shops.ProductPrice + "," +
                                            "\"QQ\":\"" + shops.QQ + "\"," +
                                            "\"Region\":\"" + shops.Region + "\"," +
                                            "\"SearchEngineType\":" + shops.SearchEngineType + "," +
                                            "\"Shipping\":" + shops.Shipping + "," +
                                            "\"ShopName\":\"" + shops.ShopName + "\"," +
                                            "\"Status\":" + (int)shops.Status + "," +
                                            "\"Url\":\"" + shops.Url + "\"," +
                                            "\"UserId\":" + shops.UserId +
                                        "}";
                        Write(result);
                        break;
                        #endregion
                    }
                case "addshops":
                    {
                        #region
                        int retcode = -1;
                        try
                        {
                            if (Request.UrlReferrer == null || string.IsNullOrEmpty(Request.UrlReferrer.AbsoluteUri))
                                return;
                            string t = Request.QueryString["t"];
                            if (string.IsNullOrEmpty(t)) return;
                            NetShopMod shop = new NetShopMod();
                            //HttpPostedFile file = Request.Files["ProductPicture"];
                            //if (file != null)
                            //{
                            //    string fileName = file.FileName;
                            //    if (!string.IsNullOrEmpty(fileName))
                            //    {
                            //        int idx = fileName.LastIndexOf(".");
                            //        string suffix = fileName.Substring(idx);//获得上传的图片的后缀名 
                            //        fileName = DateTime.Now.ToString("yyyyMMddHhmmssfff") + suffix;
                            //        shop.ProductPicture = fileName;
                            //        fileName = Server.MapPath("Uploads/") + fileName;
                            //        file.SaveAs(fileName);
                            //    }
                            //}
                            //string pricFile = UpdateFile();
                            //if (!string.IsNullOrEmpty(pricFile))
                            shop.ProductPicture = Request.Form["ProductPicture"];
                            if (t.Equals("tb"))
                                shop.NetShopType = ShopType.Taobao;
                            else
                                shop.NetShopType = ShopType.Paipai;
                            shop.UserId = SessionUser.AutoID;
                            shop.KeyWords = Request.Form["KeyWords"];
                            shop.ShopName = Request.Form["ShopName"];
                            shop.ProductName = Request.Form["ProductName"];
                            shop.Url = Request.Form["Url"];
                            shop.QQ = Request.Form["QQ"];
                            shop.Region = Request.Form["Region"];

                            if (!string.IsNullOrEmpty(Request.Form["ProductPrice"]))
                                shop.ProductPrice = double.Parse(Request.Form["ProductPrice"]);

                            if (!string.IsNullOrEmpty(Request.Form["CommitCount"]))
                                shop.CommitCount = int.Parse(Request.Form["CommitCount"]);

                            if (!string.IsNullOrEmpty(Request.Form["Shipping"]))
                                shop.Shipping = double.Parse(Request.Form["Shipping"]);

                            if (!string.IsNullOrEmpty(Request.Form["IsLogo"]))
                                shop.IsLogo = int.Parse(Request.Form["IsLogo"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsProtection"]))
                                shop.IsProtection = int.Parse(Request.Form["IsProtection"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsRetreat"]))
                                shop.IsRetreat = int.Parse(Request.Form["IsRetreat"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsAllDayShipping"]))
                                shop.IsAllDayShipping = int.Parse(Request.Form["IsAllDayShipping"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsGenuineProtection"]))
                                shop.IsGenuineProtection = int.Parse(Request.Form["IsGenuineProtection"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsCashonDelivery"]))
                                shop.IsCashonDelivery = int.Parse(Request.Form["IsCashonDelivery"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsCreditCard"]))
                                shop.IsCreditCard = int.Parse(Request.Form["IsCreditCard"]) == 1 ? true : false;

                            if (!string.IsNullOrEmpty(Request.Form["IsPublicbaby"]))
                                shop.IsPublicbaby = int.Parse(Request.Form["IsPublicbaby"]) == 1 ? true : false;
                            if (HttpDataCache.AppSettings.IsAddAudit)
                                shop.Status = KeyWordsStatus.WaitPass;
                            retcode = NetShopsBLL.Insert(shop);
                        }
                        finally
                        {
                            Response.Redirect(Request.UrlReferrer.AbsolutePath + "?retcode=" + retcode + "&url=" + Request.UrlReferrer.AbsolutePath);
                        }
                        break;

                        #endregion
                    }
                case "sc":
                    {
                        #region 检查Session
                        IList<PayTradeMod> lists = PayTradeBLL.QueryFilterToList(" Status=1 and IsInMoney=1 and UserId=" + SessionUser.AutoID);
                        int Pmoney = 0;
                        int Lmoney = 0;
                        int Balance = 0;
                        if (lists != null)
                        {
                            foreach (var tmp in lists)
                            {
                                Lmoney += tmp.RewardPoints;
                                Pmoney += tmp.Rechargepoints;
                                //Balancey += tmp.GiftPoints;
                            }
                        }
                        SessionUser = UserBLL.QueryById(SessionUser.AutoID);
                        int shops = NetShopsBLL.QueryFilterToTable(" UserId=" + SessionUser.AutoID).Rows.Count;
                        int keyWords = KeyWordsBLL.QueryFilterToTable(" UserId=" + SessionUser.AutoID).Rows.Count;
                        SystemSettingMod sysSetting = HttpDataCache.AppSettings;
                        string setting = "{\"RewardBalancePoint\":" + sysSetting.RewardBalancePoint + ",\"MoneyScale\":" + sysSetting.MoneyScale + "}";

                        string str = "{\"username\":\"" + SessionUser.Email + "\",\"balancePoint\":" + SessionUser.BalancePoint + ",\"shops\":" + shops + ",\"Lmoney\":" + Lmoney + ",\"Pmoney\":" + Pmoney + ",\"keywords\":" + keyWords + ", \"Setting\":" + setting + "}";

                        if (string.IsNullOrEmpty(Request.QueryString["format"]) || Request.QueryString["format"].Equals("js"))
                            str = "var user =" + str;
                        //string str = string.Format("Email={0}", SessionUser.Email);
                        Write(str);
                        break;
                        #endregion
                    }
                case "edituser":
                    {
                        #region 修改用户信息
                        string CompanyName = Request.Params["companyName"];
                        string Url = Request.Params["companyUrl"];
                        string QQ = Request.Params["QQ"];
                        string WangWang = Request.Params["WangWang"];
                        string MobilePhone = Request.Params["MobilePhone"];
                        string TelPhone = Request.Params["TelPhone"];
                        string NetShopName = Request.Params["NetShopName"];
                        string NetShopAddress = Request.Params["NetShopAddress"];
                        UserMod user = UserBLL.QueryById(SessionUser.AutoID);
                        int effect = -1;
                        if (user != null)
                        {
                            user.CompanyName = CompanyName;
                            user.Url = Url;
                            user.QQ = QQ;
                            user.MobilePhone = MobilePhone;
                            user.WangWang = WangWang;
                            user.TelPhone = TelPhone;
                            user.NetShopName = NetShopName;
                            user.NetShopAddress = NetShopAddress;
                            effect = UserBLL.UpdateOtherInfo(user);
                        }
                        Response.Redirect("PersonalInfo.html?act=eu&retcode=" + effect);
                        break;
                        #endregion
                    }
                case "changePass":
                    {
                        #region 修改密码
                        string passwd2 = Request.Params["passwd2"];
                        string passwd = Request.Params["passwd"];
                        string oldpasswd = Request.Params["oldpasswd"];

                        if (string.IsNullOrEmpty(oldpasswd))
                        {
                            // Response.Redirect("PersonalInfo.html?t=m&PersonalInfo.html");
                            Response.Redirect("PersonalInfo.html?act=cp&retcode=-1");
                        }
                        else if (string.IsNullOrEmpty(passwd))
                        {
                            Response.Redirect("PersonalInfo.html?act=cp&retcode=-2");
                        }
                        else if (!passwd.Equals(passwd2))
                        {
                            Response.Redirect("PersonalInfo.html?act=cp&retcode=-3");
                        }
                        else
                        {
                            UserMod user = UserBLL.QueryById(SessionUser.AutoID);
                            if (!user.Passwd.Equals(oldpasswd))
                            {
                                Response.Redirect("PersonalInfo.html?act=cp&retcode=-4");
                                return;
                            }
                            user.Passwd = passwd;
                            int effect = UserBLL.UpdatePasswd(user);
                            Response.Redirect("PersonalInfo.html?act=cp&retcode=" + effect);
                        }
                        break;
                        #endregion
                    }
                case "logout":
                    {
                        SessionUser = null;
                        Response.Redirect("index.html?t=logout");
                        break;
                    }
                case "userlogin":
                    {
                        #region 用户登录
                        string userName = Request.Params["userName"];
                        string passwd = Request.Params["passwd"];
                        int errCode;
                        if (Session["ValiCode"] == null || !Session["ValiCode"].ToString().Equals(Request.Params["vailcode"]))
                        {
                            Response.Redirect("index.html?t=m&retcode=-5&tt=" + DateTime.Now.ToString("fff"));
                            return;
                        }

                        UserMod user = UserBLL.SignUser(userName, passwd, out errCode);

                        if (user != null)
                        {
                            if (passwd.Equals(user.Passwd))
                            {
                                if (user.IsValid)
                                {
                                    LogBLL.Insert(new LogMod() { CommitDate = DateTime.Now, IpAddress = Request.UserHostAddress, UserName = user.Email });
                                    Session["user_session"] = user;
                                    Response.Redirect("Main.html?t=m&retcode=1");
                                }
                                else
                                {
                                    Response.Redirect("index.html?t=m&retcode=-3");
                                }
                            }
                            else
                            {
                                Response.Redirect("index.html?t=m&retcode=" + errCode);
                            }
                        }
                        else
                        {
                            Response.Redirect("index.html?t=m&retcode=" + errCode);
                        }
                        break;
                        #endregion
                    }
            }
            #endregion
        }
        else if (userType.Equals("um"))
        {
            #region 管理

            if (UtilHepler.GetMangerClientCookies(request, response) == null)
                if (!string.IsNullOrEmpty(action) && !action.Equals("logon"))
                {
                    Write("window.location.replace(\"index.html\")");
                    return;
                }
            switch (action)
            {
                case "s1u":
                    {
                        #region 结算
                        string status = Request.QueryString["status"];
                        switch (status)
                        {
                            case "0":
                                {
                                    lock (obj)
                                    {
                                        UtilHepler.IsComplete = true;
                                        UtilHepler.IsRunCalc = false;
                                        Write("停止结算");
                                    }
                                    break;
                                }
                            case "1":
                                {
                                    lock (obj)
                                    {
                                        if (!UtilHepler.IsRunCalc)
                                        {
                                            UtilHepler.IsComplete = false;
                                            UtilHepler.IsRunCalc = true;
                                            UtilHepler.CalculatePointsStatus = new StringBuilder();
                                            AddStatus("正在开始结算......");
                                            new Thread(new ThreadStart(RunCalc)).Start();
                                        }
                                    }
                                    break;
                                }
                            case "3":
                                {
                                    if (UtilHepler.IsComplete)
                                    {
                                        if (UtilHepler.IsRunCalc)
                                        {
                                            UtilHepler.IsRunCalc = false;
                                            Write(UtilHepler.CalculatePointsStatus.ToString());
                                        }
                                        else
                                            Write(-1);
                                    }
                                    else
                                    {
                                        Write(UtilHepler.CalculatePointsStatus.ToString());
                                    }
                                    break;
                                }
                        }
                        break;
                        #endregion
                    }
                case "su":
                    {
                        string result = "";
                        Write(result);
                        break;
                    }
                case "logon":
                    {
                        #region 登录
                        string userName = Request.Params["userName"];
                        string passwd = Request.Params["passwd"];
                        ManagerUserMod user = ManagerUserBLL.SignUser(new ManagerUserMod() { UserName = userName, Passwd = passwd });
                        int effect = -1;
                        if (user != null)
                        {
                            if (passwd.Equals(user.Passwd))
                            {
                                if (user.IsValid)
                                {
                                    UtilHepler.SetMangerClientCookies(request, response, user);
                                    //Session[UtilHepler.SESSION_NAME] = user;
                                    Response.Redirect("main.html?t=m&retcode=1");
                                }
                                else
                                {
                                    effect = -3;
                                }
                            }
                            else
                            {
                                effect = -2;
                            }
                        }
                        else
                        {
                            effect = -4;
                        }
                        Response.Redirect("index.html?retcode=" + effect);
                        break;
                        #endregion
                    }
                case "logout":
                    {
                        //Session[UtilHepler.SESSION_NAME] = null;
                        UtilHepler.SetMangerClientCookies(request, response, null);
                        Response.Redirect("index.html?t=logout");
                        break;
                    }

            }

            #endregion
        }
        else if (userType.Equals("reg"))
        {
            #region 注册
            if (action.Equals("reg"))
            {
                int effect = -100;
                try
                {
                    if (Session["ValiCode"] == null || !Session["ValiCode"].ToString().Equals(Request.Params["vailcode"]))
                    {
                        effect = -11;
                        return;
                    }
                    UserMod user = new UserMod();
                    user.CompanyName = Request.Form["CompanyName"];
                    user.Email = Request.Form["userName"];
                    user.MobilePhone = Request.Form["MobilePhone"];
                    user.NetShopAddress = Request.Form["NetShopAddress"];
                    user.NetShopName = Request.Form["NetShopName"];
                    user.Passwd = Request.Form["passwd"];
                    user.Product = Request.Form["Product"];
                    user.QQ = Request.Form["QQ"];
                    user.Recommended = Request.Form["Recommended"];
                    user.TelPhone = Request.Form["TelPhone"];
                    string understandChannel = Request.Form["UnderstandChannel"];
                    user.Url = Request.Form["Url"];
                    user.WangWang = Request.Form["WangWang"];
                    user.IsValid = true;
                    user.IsFrozen = false;
                    user.BalancePoint = 0;// HttpDataCache.AppSettings.LowPoint;
                    if (!string.IsNullOrEmpty(understandChannel))
                    {
                        if (understandChannel.Equals("1"))
                        {
                            user.UnderstandChannel = "朋友介绍";
                        }
                        else if (understandChannel.Equals("2"))
                        {
                            user.UnderstandChannel = "搜索引擎";
                        }
                        else if (understandChannel.Equals("3"))
                        {
                            user.UnderstandChannel = "金兰宣传";
                        }
                        else if (understandChannel.Equals("4"))
                        {
                            user.UnderstandChannel = "其它渠道";
                        }
                    }
                    else
                    {
                        user.UnderstandChannel = "朋友介绍";
                    }
                    if (user.BalancePoint < 0)
                        user.BalancePoint = 0;
                    if (UserBLL.CheckEmail(user) != null)
                    {
                        effect = -10;
                    }
                    else if (string.IsNullOrEmpty(user.Email))
                    {
                        effect = -1;
                    }
                    else if (string.IsNullOrEmpty(user.Passwd))
                    {
                        effect = -2;
                    }
                    else if (!user.Passwd.Equals(Request.Form["passwd2"]))
                    {
                        effect = -3;
                    }
                    else if (IsNumeric(user.Passwd))
                    {
                        effect = -4;
                    }
                    else if (IsLetter(user.Passwd))
                    {
                        effect = -4;
                    }
                    else
                    {
                        effect = UserBLL.Insert(user);
                        if (effect > 0)
                        {
                            if (HttpDataCache.AppSettings.LowPoint > 0)
                            {
                                UserMod tmp = UserBLL.QueryByEmail(user.Email);
                                if (tmp != null)
                                {
                                    PayTradeMod pay = new PayTradeMod()
                                    {
                                        Out_Trade_No = "st_" + DateTime.Now.ToString("yyyyMMddHHmmss"),
                                        RewardType = PayTradeType.Deafult,
                                        UserId = tmp.AutoID,
                                        RequestIp = Request.UserHostAddress,
                                        RewardPoints = HttpDataCache.AppSettings.LowPoint,
                                        Commit_Date = DateTime.Now,
                                        InviteId = "system",
                                        Balance = HttpDataCache.AppSettings.LowPoint,
                                        Status = false,
                                        IsInMoney = true,
                                    };
                                    if (PayTradeBLL.Insert(pay) > 0)
                                    {
                                        if (PayTradeBLL.UpdateInMoneyStatus(pay.Out_Trade_No) > 0 && PayTradeBLL.UpdatePaySuccessStatus(pay.Out_Trade_No) > 0)
                                        {
                                            UtilHepler.UpdateAccountFlow(tmp, "system", pay.RewardPoints, OperationType.Deafult);
                                        }
                                    }
                                }
                            }
                            InstallLogBLL.Insert(new InstallLogMod() { LocationMsg = UtilHepler.GetLocation(Request.UserHostAddress), UserName = user.Email, InstallSource = InstallSource.Default, IpAddress = Request.UserHostAddress, CommitDate = DateTime.Now });
                        }
                    }
                }
                finally
                {
                    Response.Redirect("register.html?retcode=" + effect);
                }
            }
            #endregion
        }
        else if (userType.Equals("pcdata"))
        {
            switch (action)
            {
                case "qu":
                    {
                        #region
                        Write(PresentChargeToJson());
                        break;
                        #endregion
                    }
                case "heplers":
                    {
                        #region
                        Write(HeplerToJson());
                        break;
                        #endregion
                    }
                case "notices":
                    {
                        #region
                        Write(NoticeToJson());
                        break;
                        #endregion
                    }
            }
        }
    }


    string SetValue(string propertyName, string value)
    {
        return "\"" + propertyName + "\":\"" + value + "\"";
    }

    string SetValue(string propertyName, DateTime value)
    {
        return SetValue(propertyName, value, DateTimeType.DateTime);
    }

    string SetValue(string propertyName, DateTime value, DateTimeType type)
    {
        if (type == DateTimeType.Date)
            return SetValue(propertyName, value.ToString("yyyy-MM-dd"));
        else if (type == DateTimeType.Time)
            return SetValue(propertyName, value.ToString("HH:mm:ss"));
        else
            return SetValue(propertyName, value.ToString("yyyy-MM-dd HH:mm:ss"));
    }

    string SetValue(string propertyName, int value)
    {
        return "\"" + propertyName + "\":" + value;
    }

    string SetValue(string propertyName, double value)
    {
        return "\"" + propertyName + "\":" + value;
    }

    string SetValue(string propertyName, bool value)
    {
        return "\"" + propertyName + "\":" + value.ToString().ToLower();
    }

    protected void InitRequestHandler(HttpContext context)
    {
        server = context.Server;
        request = context.Request;
        response = context.Response;
        sessiom = context.Session;
    }

    protected void Write(int num)
    {
        Write(num.ToString());
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="content"></param>
    protected void Write(string content)
    {
        Response.Write(content);
        HttpContext.Current.ApplicationInstance.CompleteRequest();
        //Response.End();
    }

    protected void WriteLine(string content)
    {
        Response.Write(content);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="content"></param>
    /// <param name="count"></param>
    protected void Write(byte[] content, int count)
    {
        Response.OutputStream.Write(content, 0, count);
        Response.OutputStream.Flush();
        //Response.End();
        HttpContext.Current.ApplicationInstance.CompleteRequest();
    }

    protected void Write(byte[] content)
    {
        Response.OutputStream.Write(content, 0, content != null ? content.Length : 0);
        Response.OutputStream.Flush();
        //Response.End();
        HttpContext.Current.ApplicationInstance.CompleteRequest();
    }

    protected UserMod SessionUser
    {
        get { return Session["user_session"] as UserMod; }
        set { Session["user_session"] = value; }
    }

    //protected ManagerUserMod SessionManagerUser
    //{
    //    get { return Session[UtilHepler.SESSION_NAME] as ManagerUserMod; }
    //    set { Session[UtilHepler.SESSION_NAME] = value; }
    //}

    string PayTradeToJson(string filter, int pageSize, int index)
    {
        int maxcount;
        List<PayTradeMod> pays = PayTradeBLL.QueryByPage(filter, pageSize, index == 0 ? 0 : index - 1, out maxcount);
        int MaxPage = maxcount / pageSize;
        if (maxcount % pageSize != 0)
            MaxPage += 1;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (pays == null)
        {
            sb.Append("{\"retcode\":-1}");
            return sb.ToString();
        }
        else
            sb.Append("{\"retcode\":1");
        sb.Append(",");
        sb.Append(SetValue("pageIndex", index));
        sb.Append(",");
        sb.Append(SetValue("maxcount", maxcount));
        sb.Append(",");
        sb.Append(SetValue("maxpage", MaxPage));
        sb.Append(",");
        sb.Append("\"items\":[");
        foreach (var pay in pays)
        {
            sb.Append("{");
            sb.Append(SetValue("Out_Trade_No", pay.Out_Trade_No));
            sb.Append(",");
            sb.Append(SetValue("RewardPoints", pay.RewardPoints));
            sb.Append(",");
            sb.Append(SetValue("RewardType", (int)pay.RewardType));
            sb.Append(",");
            sb.Append(SetValue("Total_fee", pay.Total_fee));
            sb.Append(",");
            sb.Append(SetValue("UserId", pay.UserId));
            sb.Append(",");
            sb.Append(SetValue("UserName", pay.UserName));
            sb.Append(",");
            sb.Append(SetValue("Body", pay.Body));
            sb.Append(",");
            sb.Append(SetValue("Commit_Date", pay.Commit_Date, DateTimeType.Date));
            sb.Append(",");
            sb.Append(SetValue("Commit_Time", pay.Commit_Date, DateTimeType.Time));
            sb.Append(",");
            sb.Append(SetValue("Commit_DateTime", pay.Commit_Date));
            sb.Append(",");
            sb.Append(SetValue("GiftPoints", pay.GiftPoints));
            sb.Append(",");
            sb.Append(SetValue("IsInMoney", pay.IsInMoney));
            sb.Append(",");
            sb.Append(SetValue("Rechargepoints", pay.Rechargepoints));
            sb.Append(",");
            sb.Append(SetValue("Status", pay.Status));
            sb.Append(",");
            sb.Append(SetValue("Subject", pay.Subject));
            sb.Append(",");
            sb.Append(SetValue("Balance", pay.Balance));
            sb.Append(",");
            sb.Append(SetValue("RequestIp", pay.RequestIp));
            sb.Append(",");
            sb.Append(SetValue("locationmsg", UtilHepler.GetLocation(pay.RequestIp)));
            sb.Append(",");
            sb.Append(SetValue("Remarks", pay.Remarks));
            sb.Append(",");
            sb.Append(SetValue("InviteId", pay.InviteId));
            sb.Append("}");
            sb.Append(",");
        }
        sb.Append("]}");
        return sb.ToString();
    }

    //string Invite_flowToJson(string filter, int pageSize, int index)
    //{
    //    int maxcount;
    //    IList<InviteFlowMod> pays = InviteFlowBLL.QueryByPage(filter, pageSize, index == 0 ? 0 : index - 1, out maxcount);
    //    int MaxPage = maxcount / pageSize;
    //    if (maxcount % pageSize != 0)
    //        MaxPage += 1;
    //    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    //    if (pays == null)
    //    {
    //        sb.Append("{\"retcode\":-1}");
    //        return sb.ToString();
    //    }
    //    else
    //        sb.Append("{\"retcode\":1");
    //    sb.Append(",");
    //    sb.Append(SetValue("pageIndex", index));
    //    sb.Append(",");
    //    sb.Append(SetValue("maxcount", maxcount));
    //    sb.Append(",");
    //    sb.Append(SetValue("maxpage", MaxPage));
    //    sb.Append(",");
    //    sb.Append("\"items\":[");
    //    foreach (var pay in pays)
    //    {
    //        sb.Append("{");
    //        sb.Append(SetValue("AutoID", pay.AutoID));
    //        sb.Append(",");
    //        sb.Append(SetValue("BalancePoint", pay.BalancePoint));
    //        sb.Append(",");
    //        sb.Append(SetValue("InviteId", pay.InviteId));
    //        sb.Append(",");
    //        sb.Append(SetValue("Remarks", pay.Remarks));
    //        sb.Append(",");
    //        sb.Append(SetValue("RequestIp", pay.RequestIp));
    //        sb.Append(",");
    //        sb.Append(SetValue("Status", pay.Status));
    //        sb.Append(",");
    //        sb.Append(SetValue("UserId", pay.UserId));
    //        sb.Append(",");
    //        sb.Append(SetValue("Commit_Date", pay.Commit_Date, DateTimeType.Date));
    //        sb.Append(",");
    //        sb.Append(SetValue("Commit_Time", pay.Commit_Date, DateTimeType.Time));
    //        sb.Append(",");
    //        sb.Append(SetValue("Commit_DateTime", pay.Commit_Date));
    //        sb.Append("}");
    //        sb.Append(",");
    //    }
    //    sb.Append("]}");
    //    return sb.ToString();
    //}

    void RunCalc()
    {
        ManagerUserMod mUser = UtilHepler.GetMangerClientCookies(request, response);
        if (mUser == null)
            return;
        string result = "正在结算用户：【{0}】 本次结算消费积分：【{1}】  结算后积分余额：【{2}】";
        List<UserMod> users = UserBLL.QueryFilterToList("");
        if (users != null && users.Count > 0)
        {
            foreach (var user in users)
            {
                try
                {
                    if (!UtilHepler.IsRunCalc) break;
                    int errcode = 0;
                    int day = AccountFlowBLL.GetDay(user.AutoID, out errcode);
                    int point = 0;
                    if (errcode == 0)
                    {
                        if (day < 1)
                        {
                            AddStatus(string.Format("该用户【{0}】今天已结算", user.Email));
                            continue;
                        }
                        if (user.BalancePoint <= 0)
                        {
                            AddStatus(string.Format("该用户【{0}】余额不足，无法结算!", user.Email));
                            continue;
                        }
                        IList<KeyWordsMod> keys = KeyWordsBLL.QueryFilterByUserId(user.AutoID);
                        IList<NetShopMod> shops = NetShopsBLL.QueryFilterByUserId(user.AutoID);
                        int count = keys != null ? keys.Count : 0;
                        point = HttpDataCache.AppSettings.EverydayKeyWordBalancePoint * count * day;
                        count = shops != null ? shops.Count : 0;
                        point += HttpDataCache.AppSettings.EverydayShopBalancePoint * count * day;
                    }
                    else
                    {
                        if (user.BalancePoint <= 0)
                        {
                            AddStatus(string.Format("该用户【{0}】余额不足，无法结算!", user.Email));
                            continue;
                        }
                        IList<KeyWordsMod> keys = KeyWordsBLL.QueryFilterByUserId(user.AutoID);
                        IList<NetShopMod> shops = NetShopsBLL.QueryFilterByUserId(user.AutoID);
                        if (keys != null)
                        {
                            foreach (var tmp in keys)
                            {
                                day = UtilHepler.GetDay(DateTime.Now, tmp.Commit_Date);
                                point += HttpDataCache.AppSettings.EverydayKeyWordBalancePoint * day;
                            }
                        }
                        if (shops != null)
                        {
                            foreach (var tmp in shops)
                            {
                                day = UtilHepler.GetDay(DateTime.Now, tmp.Commit_Date);
                                point += HttpDataCache.AppSettings.EverydayShopBalancePoint * day;
                            }
                        }
                    }
                    if (point > 0)
                        point = -point;

                    AccountFlowMod accountFlow = new AccountFlowMod()
                    {
                        Commit_Date = DateTime.Now,
                        BalancePoint = point,
                        UserId = user.AutoID,
                        UserName = user.Email,
                        OperationType = OperationType.Expense,
                        //OperationName = SessionManagerUser.UserName
                        OperationName = mUser.UserName
                    };
                    int effect = AccountFlowBLL.Insert(accountFlow);
                    if (effect > 0)
                    {
                        UserMod tmpUser = UserBLL.QueryById(user.AutoID);
                        AddStatus(string.Format(result, user.Email, Math.Abs(accountFlow.BalancePoint), tmpUser.BalancePoint));
                    }
                    Thread.Sleep(20);
                }
                catch { }
            }
        }
        if (!UtilHepler.IsRunCalc)
            AddStatus("停止结算!");
        else
            AddStatus("结算完成!");
        UtilHepler.IsComplete = true;
        UtilHepler.IsRunCalc = false;
    }

    void AddStatus(string msg)
    {
        UtilHepler.CalculatePointsStatus.AppendLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " : " + msg);
    }

    object obj = new object();
   
    string PresentChargeToJson()
    {
        List<PresentChargeMod> tmp = HttpDataCache.QueryList();
        StringBuilder sb = new StringBuilder();
        if (tmp == null)
        {
            sb.Append("{\"retcode\":-1}");
            return sb.ToString();
        }
        else
            sb.Append("{\"retcode\":1");
        sb.Append(",");
        sb.Append("\"items\":[");
        foreach (var pay in tmp)
        {
            sb.Append("{");
            sb.Append(SetValue("AutoID", pay.AutoID));
            sb.Append(",");
            sb.Append(SetValue("OneTimeMoney", pay.OneTimeMoney));
            sb.Append(",");
            sb.Append(SetValue("PresentBalancePoint", pay.PresentBalancePoint));
            sb.Append(",");
            sb.Append(SetValue("Remarks", pay.Remarks));
            sb.Append(",");
            sb.Append(SetValue("Title", pay.Title));
            sb.Append("}");
            sb.Append(",");
        }
        sb.Append("]}");
        return sb.ToString();
    }
    string NoticeToJson()
    {
        List<NoticeMod> tmp = HttpDataCache.Notices;
        StringBuilder sb = new StringBuilder();
        if (tmp == null)
        {
            sb.Append("{\"retcode\":-1}");
            return sb.ToString();
        }
        else
            sb.Append("{\"retcode\":1");
        sb.Append(",");
        sb.Append("\"items\":[");
        foreach (var pay in tmp)
        {
            sb.Append("{");
            sb.Append(SetValue("AutoID", pay.AutoID));
            sb.Append(",");
            sb.Append(SetValue("Content", pay.Content));
            sb.Append(",");
            sb.Append(SetValue("Title", pay.Title));
            sb.Append(",");
            sb.Append(SetValue("Url", pay.Url));
            sb.Append("}");
            sb.Append(",");
        }
        sb.Append("]}");
        return sb.ToString();
    }

    string HeplerToJson()
    {
        List<HeplerMod> tmp = HttpDataCache.Heplers;
        StringBuilder sb = new StringBuilder();
        if (tmp == null)
        {
            sb.Append("{\"retcode\":-1}");
            return sb.ToString();
        }
        else
            sb.Append("{\"retcode\":1");
        sb.Append(",");
        sb.Append("\"items\":[");
        foreach (var pay in tmp)
        {
            sb.Append("{");
            sb.Append(SetValue("AutoID", pay.AutoID));
            sb.Append(",");
            sb.Append(SetValue("Content", pay.Content));
            sb.Append(",");
            sb.Append(SetValue("Title", pay.Title));
            sb.Append(",");
            sb.Append(SetValue("Url", pay.Url));
            sb.Append("}");
            sb.Append(",");
        }
        sb.Append("]}");
        return sb.ToString();
    }

    bool IsLetter(string str)
    {
        //return Regex.Match(str, "^[^a-z]").Success;
        foreach (var tmp in str)
        {
            bool flag = char.IsDigit(tmp);
            if (flag)
                return false;
        }
        return true;
    }

    bool IsNumeric(string str)
    {
        System.Text.RegularExpressions.Regex reg1
            = new System.Text.RegularExpressions.Regex(@"^[-]?\d+[.]?\d*$");
        return reg1.IsMatch(str);
    }

    void WriteLogon(string msg)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<span style='color:red'>" + msg + "</span>");
        sb.Append("&nbsp;&nbsp;如果没有自动跳转请点击<a href='index.html'>返回</a>");
        sb.Append("<script>setTimeout(\"location.href='index.html'\", 5000);</script>");
        Write(sb.ToString());
    }
}